package com.atguigu.eduservice.listenter;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * @author abc
 * @version 1.0
 * @date 2021/3/8 14:59
 */

public class SubjectExcelListenter  extends AnalysisEventListener<SubjectData> {

    public EduSubjectService eduSubjectService;
    public SubjectExcelListenter(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }
    public SubjectExcelListenter() {}


    //读取数据
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext context) {
        //有数据才读取
        if(subjectData==null){
            throw new GuliException(20001,"文件数据为空");
        }
//        判断一级
        EduSubject oneSubject = this.exitOneSubject(eduSubjectService, subjectData.getOneSubjectName());
        if(oneSubject ==null){ //数据库无数据 ,就添加
            oneSubject = new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(subjectData.getOneSubjectName());
            eduSubjectService.save(oneSubject);
        }
        //取到一级分类的ID值
        String pid=oneSubject.getId();
//        判断二级
        EduSubject twoeduSubject = this.exitTwoSubject(eduSubjectService, subjectData.getTwoSubjectName(), pid);
        if(twoeduSubject ==null){ //数据库无数据 ,就添加
            twoeduSubject = new EduSubject();
            twoeduSubject.setParentId(pid);
            twoeduSubject.setTitle(subjectData.getTwoSubjectName());//二级分类
            eduSubjectService.save(twoeduSubject);
        }

    }
    //一级分类去重
    private EduSubject exitOneSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper<EduSubject> wrapper =new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject onesubject = eduSubjectService.getOne(wrapper);
        return onesubject;

    }
    //二级分类去重
    private EduSubject exitTwoSubject(EduSubjectService eduSubjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper =new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject twosubject = eduSubjectService.getOne(wrapper);
        return twosubject;

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
